<template>
  <a-row :gutter="24" >

    <a-col :md="4" :sm="24">
      <a-card :bordered="false" :loading="treeLoading">
        <a-directory-tree
          :showIcon="false"
          :treeData="treeList"
          v-if="treeList.length"
          @select="handleClick"
          :defaultExpandAll="true"
          :replaceFields="replaceFields" />
      </a-card>
    </a-col>
    <a-col :md="19" :sm="24">
      <a-card :bordered="false">
        <div class="table-page-search-wrapper">
          <a-form layout="inline">
            <a-row :gutter="48">

              <a-col :md="6" :sm="24">
                <a-form-item label="设备名称">
                  <a-select style="width: 100%" v-model="queryParam.deviceId" allow-clear placeholder="请选择设备">
                    <a-select-option v-for="(item,index) in deviceList" :key="index" :value="item.id">{{ item.deviceName }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>

              <a-col :md="10" :sm="24">
                <span class="table-page-search-submitButtons" style="padding-left: 16px;">
                  <a-form-item label="故障时间">
                    <a-range-picker v-model="queryDate" @change="handleChangeDate" style="width: 100%"/>
                  </a-form-item>
                </span>
              </a-col>

              <a-col :md="!advanced && 6 || 24" :sm="24">
                <span class="table-page-search-submitButtons" style="padding-left: 16px;" :style="advanced && { float: 'right', overflow: 'hidden' } || {} ">
                  <a-button type="primary" class="btn_search_reset" @click="exportCustom"><a-icon type="search" />导出</a-button>
                  <a-button type="primary" class="btn_search_reset" @click="$refs.table.refresh()"><a-icon type="search" />查询</a-button>
                  <a-button style="margin-left: 8px" class="btn_search_reset" @click="() => {queryParam = {deviceIds : deviceIds.toString()};queryDate = [];$refs.table.refresh()}"><a-icon type="reload" />重置</a-button>
                </span>
              </a-col>

            </a-row>
          </a-form>
        </div>

        <s-table
          ref="table"
          size="default"
          :columns="columns"
          :data="loadData"
          :alert="true"
          :rowKey="(record) => record.id"
        >
          <span slot="type" slot-scope="text">
            {{ getType(text) }}
          </span>

          <span slot="action" slot-scope="text, record">
            <a class="btn_edit" @click="exportExcel(record)">导出</a>
            <a-divider type="vertical"/>
            <a-popconfirm placement="topRight" title="确认删除？" @confirm="() => del(record)">
              <a class="btn_del">删除</a>
            </a-popconfirm>
          </span>
        </s-table>

        <add-form ref="addForm" @ok="handleOk"/>
        <edit-form ref="editForm" @ok="handleOk"/>
      </a-card>
    </a-col>
  </a-row>
</template>

<script>
  import { STable } from '@/components'
  import { page, del, exportExcel, exportCustom } from '@/api/modular/main/bizdevicestatusassess/bizDeviceStatusAssessManage'
  import addForm from './addForm'
  import editForm from './editForm'
  import { treeList } from '@/api/modular/main/bizstation/bizStationManage'
  import { deviceList } from '@/api/modular/main/bizdevice/bizDeviceManage'

  export default {
    components: {
      STable,
      addForm,
      editForm
    },

    data () {
      return {
        queryDate: [],
        data: [],
        page: {},
        loading: false,
        advanced: false, // 高级搜索 展开/关闭
        queryParam: {}, // 查询参数
        columns: [ // 表头
          {
            title: '设备名称',
            dataIndex: 'deviceName'
          },
          {
            title: '已处理故障',
            dataIndex: 'normalNumber'
          },
          {
            title: '未处理故障',
            dataIndex: 'errorNumber'
          },
          {
            title: '评估时间',
            dataIndex: 'assessTime'
          },
          {
            title: '类型',
            dataIndex: 'type',
            scopedSlots: { customRender: 'type' }
          },
          {
            title: '操作',
            dataIndex: 'action',
            width: '200px',
            scopedSlots: { customRender: 'action' }
          }
        ],
        // 加载数据方法 必须为 Promise 对象
        loadData: parameter => {
          return page(Object.assign(parameter, this.queryParam)).then((res) => {
            return res.data
          })
        },
        selectedRowKeys: [],
        selectedRows: [],
        defaultExpandedKeys: [],
        replaceFields: {
          key: 'id'
        },
        treeList: [],
        treeLoading: true,
        deviceList: [],
        deviceIds: [],
        stationTreeIndex: -1,
        stationId: 0
      }
    },
    created () {
      this.getStationTree()
    },
    methods: {
      del (record) {
        del(record).then((res) => {
          if (res.success) {
            this.$message.success('删除成功')
            this.$refs.table.refresh()
          } else {
            this.$message.error('删除失败：' + res.message)
          }
        }).catch((err) => {
          this.$message.error('删除错误：' + err.message)
        })
      },
      toggleAdvanced () {
        this.advanced = !this.advanced
      },
      handleOk () {
        this.$refs.table.refresh()
      },
      onSelectChange (selectedRowKeys, selectedRows) {
        this.selectedRowKeys = selectedRowKeys
        this.selectedRows = selectedRows
      },
      getStationTree () {
        treeList(Object.assign(this.queryParam)).then(res => {
          this.treeLoading = false
          if (!res.success) {
            return
          }
          this.treeList = res.data
        })
      },
      handleClick (e) {
        this.queryParam = {}
        this.queryDate = []
        const param = {
          stationId: e.toString()
        }
        this.stationId = e.toString()
        deviceList(param).then(res => {
          this.deviceIds = []
          this.deviceList = res.data
          for (let i = 0; i < res.data.length; i++) {
            this.deviceIds.push(res.data[i].id)
          }
          this.queryParam.deviceIds = this.deviceIds.toString()
          this.$refs.table.refresh()
        })
      },
      getType (text) {
        if (text === 0) {
          return '周报'
        } else if (text === 1) {
          return '月报'
        } else if (text === 2) {
          return '年报'
        } else {
          return '自定义'
        }
      },
      exportExcel (record) {
        exportExcel(record).then(res => {
          this.downloadXlsFile(res)
        })
      },
      downloadXlsFile (res) {
        var blob = new Blob([res.data], { type: 'application/octet-stream;charset=UTF-8' })
        var contentDisposition = res.headers['content-disposition']
        var patt = new RegExp('filename=([^;]+\\.[^\\.;]+);*')
        var result = patt.exec(contentDisposition)
        var filename = result[1]
        var downloadElement = document.createElement('a')
        var href = window.URL.createObjectURL(blob) // 创建下载的链接
        var reg = /^["](.*)["]$/g
        downloadElement.style.display = 'none'
        downloadElement.href = href
        downloadElement.download = decodeURI(filename.replace(reg, '$1')) // 下载后文件名
        document.body.appendChild(downloadElement)
        downloadElement.click() // 点击下载
        document.body.removeChild(downloadElement) // 下载完成移除元素
        window.URL.revokeObjectURL(href)
      },
      // 改变时间事件
      handleChangeDate (date, dateString) {
        this.queryParam.startTime = dateString[0]
        this.queryParam.endTime = dateString[1]
      },
      exportCustom () {
        if (this.stationId && this.queryParam.startTime && this.queryParam.endTime) {
          const from = new FormData()
          from.append('stationId', this.stationId)
          if (this.queryParam.deviceId) {
            from.append('deviceId', this.queryParam.deviceId)
          }
          from.append('startTime', this.queryParam.startTime)
          from.append('endTime', this.queryParam.endTime)
          exportCustom(from).then(res => {
            this.downloadXlsFile(res)
          })
        } else {
          this.$message.warn('请选择站点、开始时间与结束时间')
        }
      }
    }
  }
</script>

<style lang="less" scoped>
  @import '../../../assets/css/list.less';
.table-operator {
  margin-bottom: 18px;
}
button {
  margin-right: 8px;
}
  .table-page-search-wrapper{
    padding-left: 10px !important;
    .ant-row{
      margin-left: 0px !important;
    }
  }
</style>
